﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;

namespace Gildor.SimpleHostMonitor.Desktop.Entities
{
    /// <summary>
    /// A collection of <see cref="MonitorLogItem"/>. 
    /// This class is not thread-safe.
    /// </summary>
    [DebuggerDisplay ("Count = {_items.Count}")]
    public class MonitorLog :
        IEnumerable<MonitorLogItem>,
        INotifyCollectionChanged,
        INotifyPropertyChanged
    {
        private ObservableCollection<MonitorLogItem> _items;

        public MonitorLog ()
        {
            _items = new ObservableCollection<MonitorLogItem> ();
        }

        /// <summary>
        /// Adds a monitor log item to the collection
        /// </summary>
        /// <param name="monitorLogItem">The monitor log item.</param>
        public void AddLogItem (MonitorLogItem monitorLogItem)
        {
            //TODO
            //Temporary actions to prevent memory leak.
            if (_items.Count >= 100)
            {
                _items.Clear ();
            }

            _items.Add (monitorLogItem);
            OnCollectionChanged (
                new NotifyCollectionChangedEventArgs (
                NotifyCollectionChangedAction.Add, monitorLogItem));
        }

        public IEnumerator<MonitorLogItem> GetEnumerator ()
        {
            return _items.GetEnumerator ();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
        {
            return ((System.Collections.IEnumerable)_items).GetEnumerator ();
        }

        #region [CollectionChanged Event]

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        protected virtual void OnCollectionChanged (NotifyCollectionChangedEventArgs e)
        {
            if (null != CollectionChanged)
            {
                CollectionChanged (this, e);
            }
        }

        #endregion

        #region [PropertyChanged Event]

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged (PropertyChangedEventArgs e)
        {
            if (null != PropertyChanged)
            {
                PropertyChanged (this, e);
            }
        }

        #endregion
    }
}
